package com.qf.ssm.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.ssm.dto.R;
import com.qf.ssm.pojo.BaseUser;
import com.qf.ssm.pojo.Menu;
import com.qf.ssm.pojo.Role;
import com.qf.ssm.service.MenusService;
import com.qf.ssm.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class MySuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private RoleService roleService;

    private MenusService menusService;

    private ObjectMapper objectMapper;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Autowired
    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }

    @Autowired
    public void setMenusService(MenusService menusService) {
        this.menusService = menusService;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //在这里把你想在登录成功之后要做的事情做出来,必须把用户的权限查询出来保存起来
        System.err.println("登录成功了");
        BaseUser baseUser = (BaseUser) authentication.getPrincipal();//获取到当前的用户信息
        System.err.println(baseUser);
        System.err.println(authentication.getPrincipal());
        List<GrantedAuthority>grantedAuthorities=new ArrayList();//用于保存用户所有的权限的集合
        Long uid = baseUser.getUid();//获取到当前登录用户的id
        //根据用户 id 查询用户的角色,然后查询菜单
        List<Role> roles = roleService.findRoleByUserId(uid);
        roles.forEach(role -> {//遍历角色,查询每个角色的菜单,并设置进去
            List<Menu> menuList = menusService.findMenuByRoleId(role.getId());
            role.setMenuList(menuList);
            //我们需要将查询到的角色和权限设置给当前登录的用户
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_"+role.getName()));//给用户添加角色
            //设置权限
            //将所有的权限设置到用户身上
            grantedAuthorities.addAll(menuList.stream().map(Menu::getPerms).map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
        });
        baseUser.setRoleList(roles);//保存了用户的所有的角色,方便在其他地方使用
        //刷新权限,重新给用户授权
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(baseUser, authentication.getCredentials(), grantedAuthorities));
        //更新登陆时间，发送一个事件，事件中需要携带数据 用户的id
        if(request.getHeader("ismobile")!=null){
            R r = R.setOK();
            response.setContentType(MediaType.APPLICATION_JSON_UTF8.toString());
            response.getWriter().write(objectMapper.writeValueAsString(r));
        }
        response.sendRedirect("/index.html");
    }
}
